package com.sharif.cn.distributed.zookeeper;

import com.sharif.cn.local.publish.LocalReactivePublish;
import com.sharif.cn.local.subscriber.LocalReactiveSubscriber;
import javafx.fxml.LoadException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.*;
import java.util.concurrent.CountDownLatch;

public class ZookeeperSubscribe implements Watcher {
    String path;
    private static CountDownLatch latch = new CountDownLatch(1);
    private static Stat stat = new Stat();
    private static ZooKeeper zk = null;
    private final static Integer SESSION_TIMEOUT = 15000;

    private LocalReactiveSubscriber localReactiveSubscriber;



    public void publish() throws IOException, InterruptedException {
        path = "/publish";
        zk = new ZooKeeper("127.0.0.1:2181", SESSION_TIMEOUT, new ZookeeperSubscribe());
        localReactiveSubscriber = new LocalReactiveSubscriber();
        latch.await();
    }

    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && event.getPath() == null) {
                latch.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {//Clinet需要去拉取最新的数据信息
                try {
                    byte[] newByte = zk.getData(event.getPath(), true, stat);
                    ByteArrayInputStream bos = new ByteArrayInputStream(newByte);
                    ObjectInputStream oos = new ObjectInputStream(bos);
                    Object obj = oos.readObject();
                    System.out.println("path:" + event.getPath() + "\tdata has changed.\t new Data :" + obj);
                    localReactiveSubscriber.publish(obj);
                    zk.getChildren(event.getPath(), this);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        new ZookeeperSubscribe().publish();
        Thread.sleep(Long.MAX_VALUE);
    }
}
